
<template>
  <div>
    <!-- 按钮 -->
    <el-button
      type="primary"
      icon="el-icon-plus"
      class="mb-20"
      @click="showDialog"
      round
      size="medium"
      >添加</el-button
    >
    <!-- 对话框 -->

    <el-dialog
      :title="tmform.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
    >
      <el-form style="width: 80%" :model="tmform" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmform.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmform.logoUrl" :src="tmform.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" round size="medium"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="addOrUpdateTradeMark"
          round
          size="medium"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 表格 -->
    <el-table style="width: 100%" border class="mb-20" :data="list">
      <el-table-column
        label="序号"
        width="80"
        type="index"
        align="center"
      ></el-table-column>
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 80px; height: 80px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row, $index }">
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-edit"
            @click="updateTradeMark(row)"
            round
            >修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            round
            @click="deleteTradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <!-- 
      @size-change="handleSizeChange"                        pageSize 改变时会触发
      @current-change="handleCurrentChange"                  currentPage 改变时会触发
      :current-page="currentPage4"                           当前页数，支持 .sync 修饰符
      :page-sizes="[1, 2, 3, 4]"                             每页显示个数选择器的选项设置
      :page-size="4"                                         每页显示条目个数，支持 .sync 修饰符
      layout="prev, pager, next, jumper, sizes, total"       组件布局，子组件名用逗号分隔
      :total="50"                                            总条目数
      :pager-count	                                         页码按钮的数量，当总页数超过该值时会折叠 
    -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[3, 6, 9]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      :pager-count="5"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "tradeMark",
  data() {
    return {
      dialogFormVisible: false,
      page: 1,
      limit: 3,
      total: 0,
      list: [],
      // imageUrl: "",
      // 收集品牌信息
      tmform: {
        tmName: "",
        logoUrl: "",
      },
      // 表单验证规则
      rules: {
        // 品牌名称的验证规则
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10个字符",
            trigger: "change",
          },
        ],
        // 品牌logo的验证规则
        logoUrl: [{ required: true, message: "请选择品牌图片" }],
      },
    };
  },
  //  组件挂载完毕发请求
  mounted() {
    // 获取列表数据
    this.getPageList();
  },
  methods: {
    // 获取品牌列表数据
    async getPageList() {
      const { page, limit } = this;
      let result = await this.$api.reqTrademarkListApi(page, limit);
      console.log(result);
      if (result.code === 200) {
        this.total = result.data.total;
        this.list = result.data.records;
      }
    },
    handleCurrentChange(pager) {
      this.page = pager;
      // 重新获取列表数据
      this.getPageList();
    },
    // pageSize 改变时会触发
    handleSizeChange(limit) {
      this.limit = limit;
      // 重新获取列表数据
      this.getPageList();
    },
    // 点击添加品牌按钮
    showDialog() {
      // 显示对话框
      this.dialogFormVisible = true;
      // 清空数组
      this.tmform = {
        tmName: "",
        logoUrl: "",
      };
    },
    // 点击修改品牌按钮
    updateTradeMark(row) {
      // 显示对话框
      this.dialogFormVisible = true;
      this.tmform = { ...row };
    },
    // 图片上传的回调
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      //res: 上传成功之后返回前端数据
      //file:上传成功之后服务器返回前端数据
      //收集品牌图片数据
      this.tmform.logoUrl = res.data;
    },
    // 图片上传之前
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 添加或者修改品牌按钮
    addOrUpdateTradeMark() {
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          // 隐藏对话框
          this.dialogFormVisible = false;
          // 发请求（添加///修改）
          let result = await this.$api.reqAddUpdateTrademarkApi(this.tmform);
          if (result.code === 200) {
            this.$message.success(
              this.tmform.id ? "修改品牌成功" : "添加品牌成功"
            );
            // 重新获取列表数据
            this.getPageList(this.tmform.id ? this.page : 1);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除品牌
    deleteTradeMark(row) {
      this.$confirm(`你确定删除${row.tmName}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (this.list.length == 1) {
            this.page = this.page - 1;
          }
          // 点击确认按钮
          let result = await this.$api.reqDeleteTrademarkApi(row.id);
          if (result.code === 200) {
            this.$message.success("删除成功!");
          }
          // 重新获取列表数据
          this.getPageList();
        })
        .catch(() => {
          // 点击取消按钮
          this.$message.info("已取消删除");
        });
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  /* border: 1px dashed #d9d9d9; */
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>